package pre.liuxl.blog.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pre.liuxl.blog.entity.User;
import pre.liuxl.blog.service.UserFileService;
import pre.liuxl.blog.utils.QiniuyunUtil;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by liuxuanlong on 2018/6/29.
 */
@Controller
public class UserFileController {
    @Autowired
    UserFileService userFileService;

    @RequestMapping("/userFile")
    public String userFile(Model model) {
        model.addAttribute("fileList", userFileService.findAllUserFile());
        return "userFile";
    }

    @RequestMapping("/uploadUserFile")
    public String uploadUserFile(Model model) {

        return "/admin/userFile";
    }

    @RequestMapping("/fileUpload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam("file") MultipartFile file, String fileName, HttpSession session, String fileInfo) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String uploadFileName = file.getOriginalFilename();
            String suffixName = uploadFileName.substring(uploadFileName.lastIndexOf("."));
            uploadFileName = UUID.randomUUID().toString()+suffixName;
            QiniuyunUtil.uploadFiles(file.getBytes(), uploadFileName);
            stringBuilder.append("http://patkem0hy.bkt.clouddn.com/").append(uploadFileName);
            User loginUser = (User) session.getAttribute("loginUser");
            Integer loginUserId = loginUser.getId();
            userFileService.saveFile(fileName, loginUserId, fileInfo, stringBuilder.toString());
            JSONObject jsonObject = new JSONObject();
            JSONObject jsonObject1 = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("msg", "上传成功");
            jsonObject1.put("src", stringBuilder.toString());
            jsonObject.put("data", jsonObject1);
            return jsonObject;
        } catch (IOException e) {
            JSONObject jsonObject = new JSONObject();
            JSONObject jsonObject1 = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("msg", "上传失败");
            e.printStackTrace();
            return jsonObject;
        }
    }
}
